LeetCode Js-169. Majority Element
Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times.
You may assume that the majority element always exists in the array.LeetCode Js-169. Majority Element
給予一個陣列 nums 且長度為 n,回傳多數的元素。
多數的元素是一個有出現 n / 2以上次數的元素。
你可以假設多數的元素一直都存在陣列中,也就是找出符合次數為長度除以 2 的元素。
Example 1:
Input: nums = [3,2,3]
Output: 3
Solution:
var majorityElement = function(nums) {
if (nums.length === 1) return nums[0]
let box = {}
for (let i = 0; i < nums.length; i++) {
if (!box[nums[i]]) {
box[nums[i]] = 1
} else {
box[nums[i]]++
if (box[nums[i]] >= nums.length / 2) {
return nums[i]
}
}
}
};
FlowChart:
Example 1
Input: nums = [3,2,3]
nums.length = 3
step.1
i = 0
box = {}
!box[nums[0]] => !box[3] => !undefined = true
box[nums[0]] = 1 //{'3': 1}
i = 1
box = {'3': 1}
!box[nums[1]] => !box[2] => !undefined = true
box[nums[1]] = 1//{ '2': 1, '3': 1 }
i = 2
box = {'2': 1, '3': 1}
!box[nums[2]] => !box[3] => !1 => false
box[nums[2]]++ => {'2': 1, '3': 2}
(box[nums[2]] >= nums.length / 2) //{'3'} 2 >= (3/2)=> 2 >= 1.5
return nums[2] //3